package com.lei.emos.wx.config;


import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2 //swagger 生效
public class SwaggerConfig {
    @Bean
    public Docket createRestApi(){
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        // ApiInfo对象 设置页面标题
        ApiInfoBuilder builder = new ApiInfoBuilder();
        builder.title("EMOS在线办公系统");
        ApiInfo info = builder.build();
        docket.apiInfo(info);

        //api设置
        ApiSelectorBuilder selectorBuilder = docket.select();
        //所有包下的所有类
        selectorBuilder.paths(PathSelectors.any());
        //限定显示  只显示加上ApiOperation注解的方法
        selectorBuilder.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));
        docket = selectorBuilder.build();

        //swagger支持JWT
        //作用规定在请求头中获取token 参数叫token
        ApiKey apiKey = new ApiKey("token","token","header");
        List<ApiKey> apiKeys = new ArrayList<>();
        apiKeys.add(apiKey);
        docket.securitySchemes(apiKeys);

        //令牌作用域  全局
        AuthorizationScope scope = new AuthorizationScope("global","accessEverything");
        //创建AuthorizationScope数组 将scope放入
        AuthorizationScope[] scopes = {scope};
        //创建SecurityReference对象 将AuthorizationScope这个数组放入--》scopes
        SecurityReference reference = new SecurityReference("token",scopes);
        //创建refList对象放入reference
        List refList = new ArrayList();
        refList.add(reference);
        //调用SecurityContext的静态工厂方法builder()在加入securityReferences(refList)最后build()
        SecurityContext context = SecurityContext.builder().securityReferences(refList).build();
        //最后在创建数组放入SecurityContext对象--》context
        List cxtList = new ArrayList();
        cxtList.add(context);
        //在docket的securityContexts加入cxtList
        docket.securityContexts(cxtList);

        return docket;
    }
}
